package com.morristaedt.mirror.ui;

import android.content.Intent;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrixColorFilter;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.morristaedt.mirror.R;
import com.morristaedt.mirror.bean.Weather;
import com.morristaedt.mirror.configuration.ConfigurationSettings;
import com.morristaedt.mirror.modules.BirthdayModule;
import com.morristaedt.mirror.modules.DayModule;
import com.morristaedt.mirror.modules.ForecastModule;
import com.morristaedt.mirror.receiver.AlarmReceiver;
import com.squareup.picasso.Picasso;

import java.util.List;

public class MirrorActivity extends AppCompatActivity {

    private static final String TAG = "MirrorActivity";


    private ConfigurationSettings mConfigSettings;

    private TextView mBirthdayText;
    private TextView mDayText;
    private TextView mWeatherSummary;
    private ImageView mIvWeather;
    private FrameLayout mFlOne;
    private FrameLayout mFlTwo;
    private VoiceFragment voiceFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mirror);
        mConfigSettings = new ConfigurationSettings(this);
        AlarmReceiver.startMirrorUpdates(this);

        setFullScreen();
        findView();

        if (mConfigSettings.invertXKCD()) {
            //Negative of XKCD image
            float[] colorMatrixNegative = {
                    -1.0f, 0, 0, 0, 255, //red
                    0, -1.0f, 0, 0, 255, //green
                    0, 0, -1.0f, 0, 255, //blue
                    0, 0, 0, 1.0f, 0 //alpha
            };
            ColorFilter colorFilterNegative = new ColorMatrixColorFilter(colorMatrixNegative);
//            mXKCDImage.setColorFilter(colorFilterNegative); // not inverting for now
        }

        setViewState();
    }

    private void setFullScreen() {
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_IMMERSIVE;
        decorView.setSystemUiVisibility(uiOptions);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    private void findView() {
        mBirthdayText = (TextView) findViewById(R.id.birthday_text);
        mDayText = (TextView) findViewById(R.id.day_text);
        mWeatherSummary = (TextView) findViewById(R.id.weather_summary);
        mIvWeather = (ImageView) findViewById(R.id.iv_weather);
        mFlOne = (FrameLayout) findViewById(R.id.fl_one);
        mFlTwo = (FrameLayout) findViewById(R.id.fl_two);
    }


    private void setViewState() {
        Log.i(TAG, "setViewState: ");
        colorTextViews((ViewGroup) findViewById(R.id.main_layout));
        String birthday = BirthdayModule.getBirthday();
        if (TextUtils.isEmpty(birthday)) {
            mBirthdayText.setVisibility(View.GONE);
        } else {
            mBirthdayText.setVisibility(View.VISIBLE);
            mBirthdayText.setText(getString(R.string.happy_birthday, birthday));
        }

        // 时间
        mDayText.setText(DayModule.getDay());



        // 人脸识别Fragment
        if (mConfigSettings.showFaceDetection()) {
            mFlTwo.setVisibility(View.VISIBLE);
            FaceFragment faceFragment = FaceFragment.newInstance();
            this.getSupportFragmentManager().beginTransaction().replace(R.id.fl_two, faceFragment).commit();
        } else {
            mFlTwo.setVisibility(View.GONE);
        }

        if (voiceFragment == null) {
            voiceFragment = VoiceFragment.newInstance(mConfigSettings.getTtsVoice() != 0);
        }
        voiceFragment.setForecastListener(mForecastListener);
        MirrorActivity.this.getSupportFragmentManager().beginTransaction().replace(R.id.fl_one, voiceFragment).commit();
        // 语音Fragment
        if (mConfigSettings.showVoiceDetection()) {
            mFlOne.setVisibility(View.VISIBLE);
        } else {
            mFlOne.setVisibility(View.GONE);
        }


    }

    private ForecastModule.ForecastListener mForecastListener = new ForecastModule.ForecastListener() {
        @Override
        public void onWeatherToday(final Object detail) {
            Log.i(TAG, "onWeatherToday: ");

            if (detail != null) {
                MirrorActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        StringBuilder todayStr = new StringBuilder();
                        if (detail instanceof Weather) {
                            List<Weather.ResultBean> resultList = ((Weather) detail).getResult();
                            Weather.ResultBean today = resultList.get(0);

                           showPic(mIvWeather,today.getImg());
                            todayStr.append(today.getCity()).append(today.getWeather()).append(" ").append(today.getTempRange()).append("\n");
                            todayStr.append("AQI ").append(today.getAirData()).append(" ").append(today.getAirQuality());
                            if(today.getWeather().contains("雨")){
                                todayStr.append("  记得带伞\n");
                            }
                            StringBuilder sb = new StringBuilder();
                            // 穿衣指数
                            Weather.ResultBean.ExpBean.CtBean ct =  today.getExp().getCt();
                            sb.append(ct.getPrompt());
                            if (voiceFragment != null){
                                voiceFragment.showContent(sb.toString());
                            }
                        }else if (detail instanceof String){
                            todayStr.append(((String) detail).replaceAll("\""," "));
                        }
                        String weatherToday = todayStr.toString();
                        mWeatherSummary.setVisibility(View.VISIBLE);
                        mWeatherSummary.setText(weatherToday);
                    }
                });

            }
        }
    };


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        AlarmReceiver.stopMirrorUpdates(this);
        Intent intent = new Intent(this, SetUpActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void showPic(ImageView imageView,String url){
        if (imageView != null && !TextUtils.isEmpty(url)){
            if (!imageView.isShown()){
                imageView.setVisibility(View.VISIBLE);
            }
            Picasso.with(this).load(url).into(imageView);
        }
    }

    private void colorTextViews(ViewGroup mview) {
        for (int i = 0; i < mview.getChildCount(); i++) {
            View view = mview.getChildAt(i);
            if (view instanceof ViewGroup)
                colorTextViews((ViewGroup) view);
            else if (view instanceof TextView) {
                ((TextView) view).setTextColor(mConfigSettings.getTextColor());
            }
        }
    }
}
